<template>
  <div class="login-test">
    <h1>登录状态测试</h1>

    <div class="status-section">
      <h2>当前状态</h2>
      <p><strong>登录状态:</strong> {{ isLoggedIn ? '已登录' : '未登录' }}</p>
      <p><strong>用户信息:</strong></p>
      <pre>{{ JSON.stringify(user, null, 2) }}</pre>
    </div>

    <div class="actions-section">
      <h2>操作</h2>
      <el-button @click="testLogin" type="primary">测试登录</el-button>
      <el-button @click="testLogout" type="danger">测试登出</el-button>
      <el-button @click="refreshUser" type="success">刷新用户信息</el-button>
    </div>

    <div class="debug-section">
      <h2>调试信息</h2>
      <p><strong>Supabase URL:</strong> {{ supabaseUrl }}</p>
      <p><strong>Supabase Key:</strong> {{ supabaseKey.substring(0, 20) }}...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { supabase } from '@/lib/supabase'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()

const user = computed(() => userStore.user)
const isLoggedIn = computed(() => !!user.value)

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
const supabaseKey = import.meta.env.VITE_SUPABASE_ANON_KEY

const testLogin = async () => {
  try {
    const result = await userStore.login({
      email: 'helinyu@qq.com',
      password: '123456a',
    })

    if (result.success) {
      ElMessage.success('登录成功')
      console.log('登录成功，用户信息:', user.value)
    } else {
      ElMessage.error(result.message)
      console.error('登录失败:', result.message)
    }
  } catch (error) {
    ElMessage.error('登录异常: ' + error.message)
    console.error('登录异常:', error)
  }
}

const testLogout = async () => {
  try {
    await userStore.logout()
    ElMessage.success('登出成功')
  } catch (error) {
    ElMessage.error('登出失败: ' + error.message)
  }
}

const refreshUser = async () => {
  try {
    await userStore.loadUserFromStorage()
    ElMessage.success('用户信息已刷新')
  } catch (error) {
    ElMessage.error('刷新失败: ' + error.message)
  }
}

onMounted(async () => {
  console.log('页面加载，检查用户状态...')
  await userStore.loadUserFromStorage()
  console.log('当前用户状态:', user.value)
})
</script>

<style scoped>
.login-test {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.status-section,
.actions-section,
.debug-section {
  margin: 20px 0;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.status-section h2,
.actions-section h2,
.debug-section h2 {
  margin-top: 0;
  color: #333;
}

pre {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}

.el-button {
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
